package com.dyy.AI_System.service.impl;

import com.dyy.AI_System.domain.po.Documents;
import com.dyy.AI_System.domain.po.Users;
import com.dyy.AI_System.domain.po.Departments;
import com.dyy.AI_System.domain.po.DocumentCategories;
import com.dyy.AI_System.mapper.DocumentsMapper;
import com.dyy.AI_System.mapper.UsersMapper;
import com.dyy.AI_System.mapper.DepartmentsMapper;
import com.dyy.AI_System.mapper.DocumentCategoriesMapper;
import com.dyy.AI_System.service.IDocumentsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 文档表 服务实现类
 * </p>
 *
 * @author dyy
 * @since 2025-10-14
 */
@Service
public class DocumentsServiceImpl extends ServiceImpl<DocumentsMapper, Documents> implements IDocumentsService {

    @Autowired
    private UsersMapper usersMapper;
    
    @Autowired
    private DepartmentsMapper departmentsMapper;
    
    @Autowired
    private DocumentCategoriesMapper documentCategoriesMapper;
    
    // 文件存储路径
    private static final String FILE_STORAGE_PATH = "D:/AI_program/AI_System/files/";
    
    @Override
    public Map<String, Object> uploadDocument(MultipartFile file, Long departmentId, Long categoryId, 
                                            String description, String accessLevel, List<String> tags, Long uploaderId) {
        // 创建文件存储目录
        File directory = new File(FILE_STORAGE_PATH);
        if (!directory.exists()) {
            directory.mkdirs();
        }
        
        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        String fileName = UUID.randomUUID().toString() + "." + fileExtension;
        
        // 保存文件
        try {
            File targetFile = new File(FILE_STORAGE_PATH + fileName);
            file.transferTo(targetFile);
            
            // 计算文件大小
            long fileSize = targetFile.length();
            
            // 创建文档记录
            Documents document = new Documents();
            document.setTitle(originalFilename);
            document.setFileName(fileName);
            document.setFilePath(targetFile.getAbsolutePath());
            document.setFileType(fileExtension);
            document.setFileSize(fileSize);
            document.setDepartmentId(departmentId);
            document.setCategoryId(categoryId);
            document.setDescription(description);
            document.setAccessLevel(accessLevel);
            document.setTags(String.join(",", tags));
            document.setUploaderId(uploaderId);
            document.setStatus("processing");
            document.setCreatedAt(LocalDateTime.now());
            
            // 保存到数据库
            this.save(document);
            
            // 返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("id", document.getId());
            result.put("title", document.getTitle());
            result.put("status", document.getStatus());
            
            return result;
            
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败", e);
        }
    }
    
    @Override
    public IPage<Documents> pageQuery(Integer pageNum, Integer pageSize, Long departmentId, 
                                    Long categoryId, String status) {
        Page<Documents> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Documents> queryWrapper = new QueryWrapper<>();
        
        // 添加查询条件
        if (departmentId != null) {
            queryWrapper.eq("department_id", departmentId);
        }
        if (categoryId != null) {
            queryWrapper.eq("category_id", categoryId);
        }
        if (status != null && !status.isEmpty()) {
            queryWrapper.eq("status", status);
        }
        
        // 按创建时间倒序排序
        queryWrapper.orderByDesc("created_at");
        
        return this.page(page, queryWrapper);
    }
    
    @Override
    public Map<String, Object> getDocumentDetail(Long id) {
        // 查询文档基本信息
        Documents document = this.getById(id);
        if (document == null) {
            throw new RuntimeException("文档不存在");
        }
        
        // 查询关联信息
        Users uploader = usersMapper.selectById(document.getUploaderId());
        Departments department = departmentsMapper.selectById(document.getDepartmentId());
        DocumentCategories category = documentCategoriesMapper.selectById(document.getCategoryId());
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("id", document.getId());
        result.put("title", document.getTitle());
        result.put("fileType", document.getFileType());
        result.put("fileSize", document.getFileSize());
        
        // 添加上传者信息
        Map<String, Object> uploaderMap = new HashMap<>();
        uploaderMap.put("id", uploader.getId());
        uploaderMap.put("name", uploader.getName());
        result.put("uploader", uploaderMap);
        
        // 添加部门信息
        Map<String, Object> departmentMap = new HashMap<>();
        departmentMap.put("id", department.getId());
        departmentMap.put("name", department.getName());
        result.put("department", departmentMap);
        
        // 添加分类信息
        Map<String, Object> categoryMap = new HashMap<>();
        categoryMap.put("id", category.getId());
        categoryMap.put("name", category.getName());
        result.put("category", categoryMap);
        
        // 添加其他文档信息
        result.put("description", document.getDescription());
        result.put("tags", Arrays.asList(document.getTags().split("\\,")));
        result.put("accessLevel", document.getAccessLevel());
        result.put("chunkCount", document.getChunkCount());
        result.put("status", document.getStatus());
        result.put("createdAt", document.getCreatedAt());
        
        return result;
    }
    
    @Override
    public boolean deleteDocument(Long id) {
        // 查询文档信息
        Documents document = this.getById(id);
        if (document == null) {
            throw new RuntimeException("文档不存在");
        }
        
        // 删除文件
        File file = new File(document.getFilePath());
        if (file.exists()) {
            file.delete();
        }
        
        // 删除数据库记录
        return this.removeById(id);
    }
    
    @Override
    public boolean updateDocumentInfo(Long id, String title, String description, Long categoryId, 
                                    String accessLevel, List<String> tags) {
        // 查询文档信息
        Documents document = this.getById(id);
        if (document == null) {
            throw new RuntimeException("文档不存在");
        }
        
        // 更新文档信息
        document.setTitle(title);
        document.setDescription(description);
        document.setCategoryId(categoryId);
        document.setAccessLevel(accessLevel);
        document.setTags(String.join(",", tags));
        document.setUpdatedAt(LocalDateTime.now());
        
        // 保存更新
        return this.updateById(document);
    }
}
